<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>水果超市 - 商品选择</title>
  <link rel="stylesheet" href="/css/style.css">
</head>
<body>
  <div id="app" v-cloak>
    <!-- 页面头部 -->
    <div class="header">
      <div class="container clearfix">
        <h1>🍎 水果超市</h1>
        <div class="header-actions">
          <a href="/cart.html" class="btn btn-primary">
            🛒 购物车 <span v-if="cartItemCount > 0">({{ cartItemCount }})</span>
          </a>
          <a href="/admin.html" class="btn btn-default">⚙️ 管理后台</a>
        </div>
      </div>
    </div>

    <!-- 主内容区 -->
    <div class="container">
      <!-- 活动横幅（从后端读取当前生效满减活动） -->
      <div v-if="thresholdBanners && thresholdBanners.length > 0" class="card" style="margin-bottom: 12px;">
        <div class="card-header">当前活动</div>
        <div class="card-body">
          <span v-for="(b,i) in thresholdBanners" :key="i" class="product-tag" style="margin-right: 6px;">
            {{ b }}
          </span>
        </div>
      </div>
      <!-- 搜索栏 -->
      <div class="card">
        <div class="form-inline">
          <input 
            type="text" 
            class="form-control" 
            placeholder="搜索商品名称..."
            v-model="searchKeyword"
            @input="onSearchInput"
          >
          <button class="btn btn-primary" @click="searchProducts">搜索</button>
          <button class="btn btn-default" @click="resetSearch">重置</button>
        </div>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading">
        加载中...
      </div>

      <!-- 空状态 -->
      <div v-else-if="products.length === 0" class="empty-state">
        <div class="empty-state-icon">📦</div>
        <div class="empty-state-text">暂无商品</div>
      </div>

      <!-- 商品网格 -->
      <div v-else class="product-grid">
        <div v-for="product in products" :key="product.id" class="product-card">
          <!-- 商品图标 -->
          <div class="product-image">
            {{ getProductEmoji(product.category) }}
          </div>

          <!-- 商品信息 -->
          <div class="product-name" style="display: flex; align-items: center; gap: 6px;">
            <span>{{ product.name }}</span>
            <!-- 促销标签移至名称右侧显示 -->
            <template v-if="product.promotions && product.promotions.length > 0">
              <span v-for="promo in product.promotions" :key="promo.id" class="product-tag">{{ promo.name }}</span>
            </template>
            <template v-else-if="product.hasDiscount && product.discountDesc">
              <span class="product-tag">{{ product.discountDesc }}</span>
            </template>
          </div>
          <div class="text-muted" style="font-size: 12px;">{{ product.category || '水果' }}</div>

          <!-- 价格信息 -->
          <div class="product-price" v-if="product.currentPrice && product.unit">
            <span>{{ formatMoney(product.currentPrice.amount) }}/{{ product.unitName || unitName(product.unit) }}</span>
            <span v-if="product.hasDiscount && product.originalPrice && product.originalPrice.amount !== product.currentPrice.amount" 
                  class="original-price" style="margin-left: 8px; text-decoration: line-through; color: #999;">
              {{ formatMoney(product.originalPrice.amount) }}/{{ product.unitName || unitName(product.unit) }}
            </span>
          </div>
          <div class="product-price text-muted" v-else>
            暂无价格
          </div>

          <!-- 促销标签已移动到商品名右侧，避免重复展示 -->

          <!-- 添加到购物车 -->
          <div class="product-actions" v-if="product.status === 'ACTIVE'">
            <div class="form-group">
              <div class="form-inline">
                <input 
                  type="number" 
                  class="form-control" 
                  style="width: 120px;"
                  placeholder="数量"
                  v-model.number="product.quantity"
                  min="1"
                  step="1"
                >
                <span class="form-control-static" style="margin-left: 8px; color: #666;">
                  {{ product.unitName || unitName(product.unit) }}
                </span>
              </div>
            </div>
            <button class="btn btn-success btn-sm" style="width: 100%;" @click="addToCart(product)">
              加入购物车
            </button>
          </div>
          <div v-else>
            <span class="badge badge-danger">已下架</span>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 引入依赖 -->
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script src="/js/config.js"></script>
  <script src="/js/utils.js"></script>
  <script src="/js/api.js"></script>

  <!-- 页面脚本 -->
  <script>
    const { createApp } = Vue;

    createApp({
      data() {
        return {
          loading: false,
          products: [],
          searchKeyword: '',
          cartItemCount: 0,
          thresholdBanners: [],
          unitNameMap: {},
        };
      },
      
      async mounted() {
        await this.loadUnitNames();
        await this.loadData();
        this.updateCartCount();
        this.loadActivePromotions();
      },
      
      methods: {
        /**
         * 加载单位字典（code -> 中文名）
         */
        async loadUnitNames() {
          try {
            const res = await API.getAllUnits();
            const list = (res && res.data) ? res.data : [];
            this.unitNameMap = list.reduce((m, u) => {
              m[u.code] = u.name || u.code;
              return m;
            }, {});
          } catch (e) {
            this.unitNameMap = {};
          }
        },
        unitName(code) {
          return this.unitNameMap[code] || code;
        },
        /**
         * 加载数据
         */
        async loadData() {
          this.loading = true;
          try {
            // 加载带价格信息的商品数据
            const productsRes = await API.getActiveProducts();
            
            // 处理商品数据
            if (productsRes.data) {
              this.products = productsRes.data.map(p => ({
                ...p,
                quantity: 1, // 默认数量
              }));
            } else {
              this.products = [];
            }
            
            console.log('加载成功：', this.products.length, '个商品');
          } catch (error) {
            showError(error);
          } finally {
            this.loading = false;
          }
        },
        
        /**
         * 搜索商品
         */
        async searchProducts() {
          if (!this.searchKeyword.trim()) {
            this.loadData();
            return;
          }
          
          this.loading = true;
          try {
            // 使用关键词搜索接口
            const result = await API.searchByKeyword(this.searchKeyword);
            
            if (result.data) {
              this.products = result.data.map(p => ({
                ...p,
                quantity: 1,
              }));
            } else {
              this.products = [];
            }
          } catch (error) {
            showError(error);
          } finally {
            this.loading = false;
          }
        },
        
        /**
         * 搜索输入防抖
         */
        onSearchInput: debounce(function() {
          if (this.searchKeyword.trim()) {
            this.searchProducts();
          } else {
            this.loadData();
          }
        }, 500),
        
        /**
         * 重置搜索
         */
        resetSearch() {
          this.searchKeyword = '';
          this.loadData();
        },
        
        /**
         * 加载当前生效的促销规则，并提取满减活动文案
         */
        async loadActivePromotions() {
          try {
            // 读取当前生效的满减规则（启用且在有效期内）
            const res = await API.getEffectiveThresholdDiscounts();
            const rules = (res && res.data) ? res.data : [];
            this.thresholdBanners = rules.map(r => this.buildThresholdBanner(r)).filter(Boolean);
          } catch (e) {
            console.debug('加载促销规则失败或无活动');
            this.thresholdBanners = [];
          }
        },
        
        /**
         * 生成满减活动文案（根据门槛、减免、叠加性）
         */
        buildThresholdBanner(rule) {
          try {
            // 兼容两种结构：rule.thresholdDiscounts[] 或 rule.thresholdAmount/discountAmount/stackable
            if (rule.thresholdDiscounts && rule.thresholdDiscounts.length > 0) {
              const t = rule.thresholdDiscounts[0];
              const threshold = Number(t.thresholdAmount?.amount ?? t.thresholdAmount);
              const discount = Number(t.discountAmount?.amount ?? t.discountAmount);
              const stackable = !!t.stackable;
              if (threshold > 0 && discount > 0) {
                return `满${threshold}减${discount}${stackable ? '（可叠加）' : '（不可叠加）'}`;
              }
              return null;
            } else {
              const threshold = Number(rule.thresholdAmount?.amount ?? rule.thresholdAmount);
              const discount = Number(rule.discountAmount?.amount ?? rule.discountAmount);
              const stackable = !!rule.stackable;
              if (threshold > 0 && discount > 0) {
                return `满${threshold}减${discount}${stackable ? '（可叠加）' : '（不可叠加）'}`;
              }
              return null;
            }
          } catch (e) {
            return null;
          }
        },
        
        /**
         * 添加到购物车
         */
        async addToCart(product) {
          // 验证数量
          if (!isPositiveNumber(product.quantity)) {
            showError(new Error('请输入有效的数量'));
            return;
          }

          try {
            // 获取或创建购物车（使用固定用户ID）
            const cartResult = await API.getOrCreateCart();
            
            // 获取真实的 cartId
            const cartId = cartResult.data.id;
            storage.set('cartId', cartId); // 保存购物车ID

            // 添加商品到购物车（使用固定的单位）
            const result = await API.addCartItem(cartId, {
              productId: product.id,
              quantity: product.quantity,
              unit: product.unit
            });

            showSuccess(`已添加 ${product.name} 到购物车`);
            
            // 直接使用返回值更新购物车数量（性能优化：减少一次API调用）
            if (result.data && result.data.items) {
              this.cartItemCount = result.data.items.length;
              // 保存购物车ID
              if (result.data.id) {
                storage.set('cartId', result.data.id);
              }
            }
            
            product.quantity = 1;
          } catch (error) {
            showError(error);
          }
        },
        
        /**
         * 更新购物车数量徽章
         */
        async updateCartCount() {
          try {
            const userId = CONFIG.DEMO_USER_ID;
            const result = await API.getActiveCartByUser(userId);
            
            if (result.data && result.data.items) {
              this.cartItemCount = result.data.items.length;
              // 保存购物车ID
              if (result.data.id) {
                storage.set('cartId', result.data.id);
              }
            } else {
              this.cartItemCount = 0;
            }
          } catch (error) {
            console.debug('购物车不存在或为空');
            this.cartItemCount = 0;
          }
        },
        
        /**
         * 根据分类获取商品表情符号
         */
        getProductEmoji(category) {
          const emojiMap = {
            '水果': '🍎',
            '蔬菜': '🥬',
            '肉类': '🥩',
            '海鲜': '🦞',
            '饮料': '🥤',
            '零食': '🍪',
          };
          return emojiMap[category] || '🛒';
        },
        
        /**
         * 格式化金额
         */
        formatMoney(amount) {
          return formatMoney(amount);
        },
      }
    }).mount('#app');
  </script>
</body>
</html>

